import binascii
from os.path import join
from os.path import exists
import amara
import datetime
import codecs
import string

#setdefaultencoding('utf-8')  

mapparms = {}

CAT_BLOCK = 255
INB_BLOCK = 14
FIL_BLOCK = 80

clrek = {'temp_info': [''] * 255}
coord_info = {'coord_data1': [''] * 3,
              'coord_data2': [''] * 3,
              'coord_data3': [''] * 3,
              'coord_data4': [''] * 3,
              'coord_dataN': [''] * 2}

catalog_location = []
coord_array = []
l = []
index_rec_holder = {'tmp_nm': [''] * 50,
                    'tmp_xx': [''] * 30}
atb = [''] * 9
ofc = [''] * 300
os = ''

def mbf4_as_float(s):
    m0, m1, m2, m3 = [ord(c) for c in s]
    exponent = m3
    if not exponent:
        return 0.0
    sign = m2 & 0x80
    m2 |= 0x80
    mant = (((m2 << 8) | m1) << 8) | m0
    adj = 24 + 128
    num = mant * 2.0 ** (exponent - adj)
    if sign:
        return -num
    return num 

class Geodex:
    contact = {}
    contact['organization'] = ''
    contact['person'] = ''
    contact['addresstype'] = ''
    contact['address'] = ''
    contact['city'] = ''
    contact['state'] = ''
    contact['postalcode'] = ''
    contact['country'] = ''
    contact['voice'] = ''
    contact['fax'] = ''
    contact['email'] = ''
    
    def output(self):
        print "Title: %s" % self.title
        print "Sheet: %s" % self.sheet
        print "Holdings: %d" % self.holdings
        print "Map type: %s" % self.map_type
        print "Media type: %s" % self.media_type
        print "Projection: %s" % self.projection
        print "Prime meridian: %s" % self.prime_meridian
        print "Map format: %s" % self.map_format
        print "South: %f" % self.south
        print "North: %f" % self.north
        print "West: %f" % self.west
        print "East: %f" % self.east
        print "Edition: %d" % self.edition
        print "Year: %d" % self.year
        print "Printed: %d" % self.printed
        print "Compiled from map: %d" % self.map
        print "Publication: %d" % self.publication
        print "Revised: %d" % self.revised
        print "Situation/survey: %d" % self.situation_survey
        print "Scale: %d" % self.scale
        print "Dimension code: %s" % self.dimension_code
        print "Latitudinal dimension: %d" % self.latitudinal_dimension
        print "Longitudinal dimension: %d" % self.longitudinal_dimension
        print "Call number: %s" % self.call_number
        print "Catalog title: %s" % self.cat_title
        print "Catalog entry: %s" % self.cat_entry
        print ""

    def to_fgdc(self, abstract_txt, purpose_txt, themekey_txt, filename):
        doc = amara.create_document(u'metadata')

        idinfo = doc.xml_create_element(u'idinfo')
        citation = doc.xml_create_element(u'citation')
        citeinfo = doc.xml_create_element(u'citeinfo')

        origin = doc.xml_create_element(u'origin')
        origin.xml_append(unicode(self.cat_entry, 'cp437'))
        citeinfo.xml_append(origin)

        pubdate = doc.xml_create_element(u'pubdate')
        pubdate.xml_append(unicode(self.revised) + '0101')
        citeinfo.xml_append(pubdate)

        title = doc.xml_create_element(u'title')
        title.xml_append(unicode('%s--%s' % (self.title, self.cat_title), 'cp437'))
#        print unicode('%s--%s' % (self.title, self.cat_title), 'cp437')
        citeinfo.xml_append(title)

        geoform = doc.xml_create_element(u'geoform')
        geoform.xml_append(u'map')
        citeinfo.xml_append(geoform)

        pubinfo = doc.xml_create_element(u'pubinfo')
        pubplace = doc.xml_create_element(u'pubplace')
        pubplace.xml_append(u'Unknown')
        publish = doc.xml_create_element(u'publish')
        publish.xml_append(unicode(self.cat_entry, 'cp437'))
        pubinfo.xml_append(pubplace)
        pubinfo.xml_append(publish)
        citeinfo.xml_append(pubinfo)        

        onlink = doc.xml_create_element(u'onlink')
        onlink.xml_append(u'')
        edition = doc.xml_create_element(u'edition')
        edition.xml_append(unicode(self.edition))
        citeinfo.xml_append(edition)
        citeinfo.xml_append(onlink)

        citation.xml_append(citeinfo)
        idinfo.xml_append(citation)

        descript = doc.xml_create_element(u'descript')
        abstract = doc.xml_create_element(u'abstract')
        abstract.xml_append(unicode(abstract_txt))
        descript.xml_append(abstract)
        purpose = doc.xml_create_element(u'purpose')
        purpose.xml_append(unicode(purpose_txt))
        descript.xml_append(purpose)
        supplinf = doc.xml_create_element(u'supplinf')

        supplinf_list = [self.map_type, self.media_type, self.map_format, 
                         '%s %s' % (self.latitudinal_dimension, self.dimension_code),
                         '%s %s' % (self.longitudinal_dimension, self.dimension_code)]

        if self.edition != 0:
            supplinf_list.append('Edition number %d' % self.edition)
        if self.revised != 0:
            supplinf_list.append('Revised %d' % self.revised)
        if self.situation_survey != 0:
            supplinf_list.append('Situation/Survey %d' % self.situation_survey)
        if self.call_number != 0:
            supplinf_list.append(self.call_number)

        supplinf.xml_append(unicode(string.join(supplinf_list, ', ')))
        descript.xml_append(supplinf)

        idinfo.xml_append(descript)

        timeperd = doc.xml_create_element(u'timeperd')
        timeinfo = doc.xml_create_element(u'timeinfo')
        rngdates = doc.xml_create_element(u'rngdates')
        begdate = doc.xml_create_element(u'begdate')
#        begdate.xml_append(unicode(self.ui.begdateDateEdit.date().toString('yyyyMMdd')))
        begdate.xml_append(unicode(self.situation_survey) + '0101')
        rngdates.xml_append(begdate)
        enddate = doc.xml_create_element(u'enddate')
#        enddate.xml_append(unicode(self.ui.enddateDateEdit.date().toString('yyyyMMdd')))
        enddate.xml_append(unicode(self.revised) + '0101')
        rngdates.xml_append(enddate)
        timeinfo.xml_append(rngdates)
        timeperd.xml_append(timeinfo)

        current = doc.xml_create_element(u'current')
        current.xml_append(u'publication date')
        timeperd.xml_append(current)
        idinfo.xml_append(timeperd)

        status = doc.xml_create_element(u'status')
        progress = doc.xml_create_element(u'progress')
        progress.xml_append(u'')
        status.xml_append(progress)
        update = doc.xml_create_element(u'update')
        update.xml_append(unicode(datetime.date.today().strftime('%m%d%Y')))
        status.xml_append(update)
        idinfo.xml_append(status)

        spdom = doc.xml_create_element(u'spdom')
        bounding = doc.xml_create_element(u'bounding')
        westbc = doc.xml_create_element(u'westbc')
        westbc.xml_append(unicode(self.west))
        bounding.xml_append(westbc)
        eastbc = doc.xml_create_element(u'eastbc')
        eastbc.xml_append(unicode(self.east))
        bounding.xml_append(eastbc)
        northbc = doc.xml_create_element(u'northbc')
        northbc.xml_append(unicode(self.north))
        bounding.xml_append(northbc)
        southbc = doc.xml_create_element(u'southbc')
        southbc.xml_append(unicode(self.south))
        bounding.xml_append(southbc)
        spdom.xml_append(bounding)
        idinfo.xml_append(spdom)

        keywords = doc.xml_create_element(u'keywords')
        theme = doc.xml_create_element(u'theme')
        themekt = doc.xml_create_element(u'themekt')
        themekt.xml_append(u'LCHS')
        theme.xml_append(themekt)

        themekey = doc.xml_create_element(u'themekey')
        themekey.xml_append(unicode(themekey_txt))
        theme.xml_append(themekey)

        keywords.xml_append(theme)
        place = doc.xml_create_element(u'place')
        placekt = doc.xml_create_element(u'placekt')
        placekt.xml_append(u'')
        place.xml_append(placekt)

        placekey = doc.xml_create_element(u'placekey')
        placekey.xml_append(u'')
        place.xml_append(placekey)

        keywords.xml_append(place)
        idinfo.xml_append(keywords)

        accconst = doc.xml_create_element(u'accconst')
        accconst.xml_append(u'None')
        idinfo.xml_append(accconst)

        useconst = doc.xml_create_element(u'useconst')
        useconst.xml_append(u'None')
        idinfo.xml_append(useconst)

        doc.metadata.xml_append(idinfo)

        dataqual = doc.xml_create_element(u'dataqual')
        logic = doc.xml_create_element(u'logic')
        dataqual.xml_append(logic)
        complete = doc.xml_create_element(u'complete')
        dataqual.xml_append(complete)
        
        lineage = doc.xml_create_element(u'lineage')
        srcinfo = doc.xml_create_element(u'srcinfo')
        srcscale = doc.xml_create_element(u'srcscale')
        srcscale.xml_append(unicode(self.scale))
        srcinfo.xml_append(srcscale)
        typesrc = doc.xml_create_element(u'typesrc')
        srcinfo.xml_append(typesrc)
        srctime = doc.xml_create_element(u'srctime')

        srccurr = doc.xml_create_element(u'srccurr')
        srctime.xml_append(srccurr)

        srctime.xml_append(timeinfo)

        srcinfo.xml_append(srctime)
        srccite = doc.xml_create_element(u'srccite')
        srccite.xml_append(citeinfo)

        srcinfo.xml_append(srccite)
        srccitea = doc.xml_create_element(u'srccitea')
        srcinfo.xml_append(srccitea)
        srccontr = doc.xml_create_element(u'srccontr')
        srcinfo.xml_append(srccontr)
        
        lineage.xml_append(srcinfo)

        procstep = doc.xml_create_element(u'procstep')
        procdesc = doc.xml_create_element(u'procdesc')
        procdate = doc.xml_create_element(u'procdate')
        procstep.xml_append(procdesc)
        procstep.xml_append(procdate)
        lineage.xml_append(procstep)

        dataqual.xml_append(lineage)
        doc.metadata.xml_append(dataqual)

        spdoinfo = doc.xml_create_element(u'spdoinfo')
        direct = doc.xml_create_element(u'direct')
        direct.xml_append(unicode('Raster'))
        spdoinfo.xml_append(direct)
        rastinfo = doc.xml_create_element(u'rastinfo')
        rowcount = doc.xml_create_element(u'rowcount')
        rowcount.xml_append(u'0')
        rastinfo.xml_append(rowcount)
        colcount = doc.xml_create_element(u'colcount')
        colcount.xml_append(u'0')
        rastinfo.xml_append(colcount)
        rasttype = doc.xml_create_element(u'rasttype')
        rasttype.xml_append(unicode('Pixel'))
        rastinfo.xml_append(rasttype)
        spdoinfo.xml_append(rastinfo)
        
        doc.metadata.xml_append(spdoinfo)

        distinfo = doc.xml_create_element(u'distinfo')
        distrib = doc.xml_create_element(u'distrib')
        cntinfo = doc.xml_create_element(u'cntinfo')
        cntperp = doc.xml_create_element(u'cntperp')
        contact = self.contact
        cntper = doc.xml_create_element(u'cntper')
        cntper.xml_append(unicode(contact['person']))
        cntperp.xml_append(cntper)
        cntorg = doc.xml_create_element(u'cntorg')
        cntorg.xml_append(unicode(contact['organization']))

        cntaddr = doc.xml_create_element(u'cntaddr')
        addrtype = doc.xml_create_element(u'addrtype')
        addrtype.xml_append(unicode(contact['addresstype']))
        cntaddr.xml_append(addrtype)
        address = doc.xml_create_element(u'address')
        address.xml_append(unicode(contact['address']))
        cntaddr.xml_append(address)
        city = doc.xml_create_element(u'city')
        city.xml_append(unicode(contact['city']))
        cntaddr.xml_append(city)
        state = doc.xml_create_element(u'state')
        state.xml_append(unicode(contact['state']))
        cntaddr.xml_append(state)
        postal = doc.xml_create_element(u'postal')
        postal.xml_append(unicode(contact['postalcode']))
        cntaddr.xml_append(postal)
        country = doc.xml_create_element(u'country')
        country.xml_append(unicode(contact['country']))
        cntaddr.xml_append(country)
        
        cntinfo.xml_append(cntperp)
        cntinfo.xml_append(cntaddr)

        cntvoice = doc.xml_create_element(u'cntvoice')
        cntvoice.xml_append(unicode(contact['voice']))
        cntinfo.xml_append(cntvoice)
        cntfax = doc.xml_create_element(u'cntfax')
        cntfax.xml_append(unicode(contact['fax']))
        cntinfo.xml_append(cntfax)
        cntemail = doc.xml_create_element(u'cntemail')
        cntemail.xml_append(unicode(contact['email']))
        cntinfo.xml_append(cntemail)

        distrib.xml_append(cntinfo)

        distinfo.xml_append(distrib)

        resdesc = doc.xml_create_element(u'resdesc')
        resdesc.xml_append(u'')
        distinfo.xml_append(resdesc)

        distliab = doc.xml_create_element(u'distliab')
        distliab.xml_append(u'')
        distinfo.xml_append(distliab)

        doc.metadata.xml_append(distinfo)

        metainfo = doc.xml_create_element(u'metainfo')
        metd = doc.xml_create_element(u'metd')
        metd.xml_append(u'')        
        metainfo.xml_append(metd)

        metc = doc.xml_create_element(u'metc')
        cntinfo = doc.xml_create_element(u'cntinfo')
        cntperp = doc.xml_create_element(u'cntperp')
        contact = self.contact
        cntper = doc.xml_create_element(u'cntper')
        cntper.xml_append(unicode(contact['person']))
        cntperp.xml_append(cntper)
        cntorg = doc.xml_create_element(u'cntorg')
        cntorg.xml_append(unicode(contact['organization']))

        cntaddr = doc.xml_create_element(u'cntaddr')
        addrtype = doc.xml_create_element(u'addrtype')
        addrtype.xml_append(unicode(contact['addresstype']))
        cntaddr.xml_append(addrtype)
        address = doc.xml_create_element(u'address')
        address.xml_append(unicode(contact['address']))
        cntaddr.xml_append(address)
        city = doc.xml_create_element(u'city')
        city.xml_append(unicode(contact['city']))
        cntaddr.xml_append(city)
        state = doc.xml_create_element(u'state')
        state.xml_append(unicode(contact['state']))
        cntaddr.xml_append(state)
        postal = doc.xml_create_element(u'postal')
        postal.xml_append(unicode(contact['postalcode']))
        cntaddr.xml_append(postal)
        country = doc.xml_create_element(u'country')
        country.xml_append(unicode(contact['country']))
        cntaddr.xml_append(country)
        
        cntinfo.xml_append(cntperp)
        cntinfo.xml_append(cntaddr)

        cntvoice = doc.xml_create_element(u'cntvoice')
        cntvoice.xml_append(unicode(contact['voice']))
        cntinfo.xml_append(cntvoice)
        cntfax = doc.xml_create_element(u'cntfax')
        cntfax.xml_append(unicode(contact['fax']))
        cntinfo.xml_append(cntfax)
        cntemail = doc.xml_create_element(u'cntemail')
        cntemail.xml_append(unicode(contact['email']))
        cntinfo.xml_append(cntemail)

        metc.xml_append(cntinfo)

        metstdn = doc.xml_create_element(u'metstdn')
        metstdn.xml_append(u'FGDC Content Standard for Digital Geospatial Metadata')
        metainfo.xml_append(metstdn)
        
        metstdv = doc.xml_create_element(u'metstdv')
        metstdv.xml_append(u'FGDC-STD-001-1998')
        metainfo.xml_append(metstdv)

        metainfo.xml_append(metc)
        
        doc.metadata.xml_append(metainfo)

        file = codecs.open(filename, encoding='utf-8', mode='w')
        file.write(unicode(doc.xml(indent=u'yes'), 'utf-8'))
        file.close()
        

def val(s):
    return int(binascii.b2a_hex(s), 16)

def import_geodex_local(filename, theme_str, geography_str, subject_str,
                        author_str, holding_str,
                        abstract_str, purpose_str, keywords_str, output_dir,
                        progress):
    os = ''
    mapparms_file = open('mapparms', 'rU')
    for line in mapparms_file.readlines():
        if len(line) >= 3:
            num = int(line[0:3])
            value = line[4:]
            mapparms[num] = value

    inb_file = open(filename + '.INB', 'rb')
    inb_contents = inb_file.read()
    num_of_coord_records = len(inb_contents) / INB_BLOCK
    inb_file.seek(0)

    print "Reading %d records..." % num_of_coord_records

    fil_file = open(filename + '.FIL', 'rb')
    fil_contents = fil_file.read()
    fil_file.seek(0)

    cat_file = open(filename + '.CAT', 'rb')
    cat_contents = cat_file.read()
    num_of_cat_records = len(cat_contents) / CAT_BLOCK
    cat_file.seek(0)

    for n in range(1, num_of_cat_records):
        cat_file.seek(CAT_BLOCK * n)
        clrek['temp_info'][n] = cat_file.read(CAT_BLOCK)
        temp_clrek = clrek['temp_info'][n].strip()
        catalog_location.append(temp_clrek.split('\\'))

    if progress:
        progress.setMaximum(num_of_coord_records)

    for n in range(0, num_of_coord_records):
        #        print "Record %d" % n
        if progress:
            progress.setLabelText("Importing %d / %d" % (n, num_of_coord_records))
            progress.setValue(n+1)
            
            if progress.wasCanceled():
                break

        geodex = Geodex()

        coord_array = []
        coord_array.append(inb_file.read(3))
        coord_array.append(inb_file.read(3))
        coord_array.append(inb_file.read(3))
        coord_array.append(inb_file.read(3))
        coord_info['coord_dataN'] = inb_file.read(2)

#        print "Loading coordinate information..."
    
        l = []
        for m in range(0, 4):
            la = ord(coord_array[m][0]) * 65536
            lb = ord(coord_array[m][1]) * 256
            lc = ord(coord_array[m][2])
            l.append(la + lb + lc)
            
            if m < 2 and l[m] >= 648000:
#                print l[m]
                l[m] = (l[m] - 648000) / 3600.
            if m < 2 and l[m] < 648000:
                l[m] = (324000 - l[m]) / 3600. * -1
            if m > 1 and l[m] < 648000:
                l[m] = (324000 - l[m]) / 3600. * -1
            if m > 1 and l[m] >= 648000:
                l[m] = (l[m] - 648000) / 3600.

        geodex.south = l[0]
        geodex.north = l[1]
        geodex.west = l[2]
        geodex.east = l[3]

        tmp_index_start = val(coord_info['coord_dataN'][0:2][::-1]) - 1
#        print "tmp_index_start: ", tmp_index_start
                            
        fil_file.seek(FIL_BLOCK * tmp_index_start)
        
        index_rec_holder['tmp_nm'] = fil_file.read(50)
        index_rec_holder['tmp_xx'] = fil_file.read(30)
        
#        print "Loading index data..."
        
        xx = index_rec_holder['tmp_xx']
        nm = index_rec_holder['tmp_nm']

        geodex.holdings = val(xx[0:2][::-1])
#        print hld
        
#        if hld in range(1, 99):
#            atb[0] = "GZN"

#        for r in range(1, 6):
#            atb[r] = mapparms[ord(xx[r+1])]
            
#        print val(xx)
        geodex.scale = int(mbf4_as_float(xx[8:12]))

        if ord(xx[3]) != 0:
            geodex.map_type = mapparms[ord(xx[3])].strip()
        else:
            geodex.map_type = ''

        if ord(xx[4]) != 0:
            geodex.media_type = mapparms[ord(xx[4])].strip()
        else:
            geodex.media_type = ''

        if ord(xx[5]) != 0:
            geodex.projection = mapparms[ord(xx[5])].strip()
        else:
            geodex.projection = ''
        
        if ord(xx[6]) != 0:
            geodex.prime_meridian = mapparms[ord(xx[6])].strip()    
        else:
            geodex.prime_meridian = ''

        if ord(xx[7]) != 0:
            geodex.map_format = mapparms[ord(xx[7])].strip()
        else:
            geodex.map_format = ''

        if ord(xx[12]) != 0:
            geodex.dimension_code = mapparms[ord(xx[12])].strip()
            geodex.latitudinal_dimension = ord(xx[13])
            geodex.longitudinal_dimension = ord(xx[14])
        else:
            geodex.dimension_code = ''
            geodex.latitudinal_dimension = 0
            geodex.longitudinal_dimension = 0

        dc = ord(xx[12])
        ad = ord(xx[13])
        od = ord(xx[14])

        if dc == 52:
            dc = 53
            ad = ad / 6
            od = od / 6

#        atb[7] = str(ad)[0:2] + ' ' + mapparms[dc]
#        atb[8] = str(od)[0:2] + ' ' + mapparms[dc]
        
        for r in range(0, 4):
            oft = ord(xx[16 + ((r - 1) * 3)])
            if oft == 66:
                oft = 92
            if oft == 67:
                oft = 93
            if oft == 68:
                oft = 94
            if oft == 70:
                oft = 95
            if oft == 77:
                oft = 96

            ofv = str(val(xx[17 + ((r - 1) * 3):17 + ((r-1)*3) + 1]))[0:2]
            ofc[oft] = ofv

            for r in range(91, 122):
                if oft == 0:
                    oft = 91
                    
                if r == 122:
                    os = os + ofc[r]
                    
                os = os + ofc[r] + chr(34) + ',' + chr(34)
                ofc[r] = ''

            for dd in range(10, 5, -1):
                dt = str(val(xx[(3 * dd) - 1:(3*dd) - 1 + 3]))[0:2]
                if dt > '0':
                    nm = nm.strip()

            geodex.publicationdate = dt

            if nm.endswith('\0'):
                nm = nm[:-1]

            a = nm.find(chr(196))
            if a > 0:
                cmt = nm[a]
                nm = nm[0:a]
                
            a = nm.find(chr(250))
            if a > 0:
                nm1 = nm[0:a]
                nm2 = nm[a+1:]
                sbuffer = catalog_location[val(xx[2])-1][2]

        a = xx[15:].find('e')
        if a >= 0 and a % 3 == 0:
            geodex.edition = int(binascii.b2a_hex(xx[15:][a+2] + xx[15:][a+1]), 16)
        else:
            geodex.edition = 0
            
        a = xx[15:].find('r')
        if a >= 0 and a % 3 == 0:
            geodex.revised = int(binascii.b2a_hex(xx[15:][a+2] + xx[15:][a+1]), 16)
        else:
            geodex.revised = 0

        a = xx[15:].find('s')
        if a >= 0 and a % 3 == 0:
            geodex.situation_survey = int(binascii.b2a_hex(xx[15:][a+2] + xx[15:][a+1]), 16)
        else:
            geodex.situation_survey = 0

        a = xx[15:].find('y')
        if a >= 0 and a % 3 == 0:
            geodex.year = int(binascii.b2a_hex(xx[15:][a+2] + xx[15:][a+1]), 16)
        else:
            geodex.year = 0

        a = xx[15:].find('p')
        if a >= 0 and a % 3 == 0:
            geodex.printed = int(binascii.b2a_hex(xx[15:][a+2] + xx[15:][a+1]), 16)
        else:
            geodex.printed = 0

        a = xx[15:].find('m')
        if a >= 0 and a % 3 == 0:
            geodex.map = int(binascii.b2a_hex(xx[15:][a+2] + xx[15:][a+1]), 16)
        else:
            geodex.map = 0

        a = xx[15:].find('b')
        if a >= 0 and a % 3 == 0:
            geodex.publication = int(binascii.b2a_hex(xx[15:][a+2] + xx[15:][a+1]), 16)
        else:
            geodex.publication = 0

        geodex.title = '%s' % nm2
        geodex.sheet = '%s' % nm1
        geodex.cat_entry = catalog_location[val(xx[2])-1][1]
#            geodex.originator = catalog_location[val(xx[2])-1][1]
        geodex.call_number = catalog_location[val(xx[2]) - 1][0]
        geodex.cat_title = catalog_location[val(xx[2]) - 1][2]
            
#        geodex.output()

        filename_theme = theme_str
        filename_geography = geography_str
        filename_subject = subject_str
        filename_scale = 's%d' % (int(geodex.scale) / 1000)
        filename_id = geodex.sheet

        if geodex.revised != 0:
            filename_date = geodex.revised
        elif geodex.printed != 0:
            filename_date = geodex.printed
        elif geodex.year != 0:
            filename_date = geodex.year
        elif geodex.publication != 0:
            filename_date = geodex.publication
        elif geodex.situation_survey != 0:
            filename_date = geodex.situation_survey
        elif geodex.map != 0:
            filename_date = geodex.map

        filename_author = author_str
        filename_holding = holding_str

        filename_copy = 1

        output_filename = "%s_%s_%s_%s_%s_%s_%s_%s_%d.xml" % (filename_theme,
                                                              filename_geography,
                                                              filename_subject,
                                                              filename_scale,
                                                              filename_id,
                                                              filename_date,
                                                              filename_author,
                                                              filename_holding,
                                                              filename_copy)
        
        while exists(join(output_dir, output_filename)):
            filename_copy = filename_copy + 1
            output_filename = "%s_%s_%s_%s_%s_%s_%s_%s_%d.xml" % (filename_theme,
                                                                  filename_geography,
                                                                  filename_subject,
                                                                  filename_scale,
                                                                  filename_id,
                                                                  filename_date,
                                                                  filename_author,
                                                                  filename_holding,
                                                                  filename_copy)

        geodex.to_fgdc(abstract_str, purpose_str, keywords_str, join(output_dir, output_filename))
    
    mapparms_file.close()
    inb_file.close()
    fil_file.close()

def test():
    import_geodex_local('geodex_output/F0005',
                               '',
                               '', 
                               '',
                               '',
                               '',
                               '',
                               '',
                               '',
                               str('geodex_output'),
                               None)
#    import_geodex_local('F0005')
